package top.viya.hello2.statemachine.ssm;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.state.State;

import java.util.Arrays;
import java.util.HashSet;

/**
 * 直接使用string类型定义状态和事件
 */
@EnableStateMachine(name = "stateMachine2")
@Configuration
public class StateMachineConfig2 extends StateMachineConfigurerAdapter<String, String> {


    @Override
    public void configure(StateMachineConfigurationConfigurer<String, String> config)
            throws Exception {
        config.withConfiguration()
                .autoStartup(true)
                .listener(listener2());
    }

    @Override
    public void configure(StateMachineStateConfigurer<String, String> states)
            throws Exception {
        states.withStates()
                .initial("SI")
                .end("SF")
                .states(new HashSet<String>(Arrays.asList("S1", "S2", "S3", "S4")));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<String, String> transitions)
            throws Exception {
        transitions.withExternal()
                .source("SI").target("S1").event("E1")
                .and()
                .withExternal()
                .source("S1").target("S2").event("E2")
                .and()
                .withExternal()
                .source("S2").target("S3").event("E3")
                .and()
                .withExternal()
                .source("S3").target("S4").event("E4")
                .and()
                .withExternal()
                .source("S4").target("SF").event("E5");
    }

    @Bean
    public StateMachineListener<String, String> listener2() {
        return new StateMachineListenerAdapter<String, String>() {
            @Override
            public void stateChanged(State<String, String> from, State<String, String> to) {
                System.out.println("SM2 State change to " + to.getId());
            }
        };
    }


}
